package com.dm.wallpaper.library.adapters;

import com.dm.wallpaper.library.ResourceTable;
import com.dm.wallpaper.library.database.Database;
import com.dm.wallpaper.library.items.Category;
import com.dm.wallpaper.library.items.Filter;
import com.nostra13.universalimageloader.core.ImageLoader;
import ohos.agp.components.*;
import ohos.app.Context;

import java.util.List;

public class CategoriesListAdapter extends RecycleItemProvider {

    private List<Category> data;

    private LayoutScatter layoutScatter;


    public CategoriesListAdapter(Context context, List<Category> data) {
        this.data = data;
        this.layoutScatter = LayoutScatter.getInstance(context);
    }

    @Override
    public int getCount() {
        return data != null ? data.size() : 0;
    }

    @Override
    public Object getItem(int i) {
        return data != null ? data.get(i) : null;
    }

    @Override
    public long getItemId(int i) {
        return i;
    }


    @Override
    public Component getComponent(int position, Component component, ComponentContainer componentContainer) {
        ViewHolder viewHolder = null;
        if (component == null) {
            component = layoutScatter.parse(ResourceTable.Layout_categories_item_layout, null, false);
            viewHolder = new ViewHolder((ComponentContainer) component);
            component.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) component.getTag();
        }
        Category category = data.get(position);
//        int localId = category.getLocalid();
//        if (localId == 0) {
//            //  viewHolder.image.setLayoutConfig(layoutConfig);
//            viewHolder.image.setImageAndDecodeBounds(0);
//        } else {
//            // image_Category_show.setLayoutConfig(layoutConfig);
//            viewHolder.image.setImageAndDecodeBounds(localId);
//        }
        ImageLoader.getInstance().displayImage(category.getThumbUrl(), viewHolder.image);
        viewHolder.tvItemName.setText(category.getName());


        Filter filter = new Filter();
        filter.add(Filter.Create(Filter.Column.CATEGORY).setQuery(category.getName()));
        category.setCount(Database.get().getFilteredWallpapersCount(filter));
        String count = category.getCount() + " " + "Wallpapers";

        viewHolder.tvItemCount.setText(count);
        return component;
    }


    static class ViewHolder {

        Text tvItemName;
        Text tvItemCount;
        Image image;

        public ViewHolder(ComponentContainer componentContainer) {
            tvItemName = (Text) componentContainer.findComponentById(ResourceTable.Id_tv_name);
            tvItemCount = (Text) componentContainer.findComponentById(ResourceTable.Id_tv_count);
            image = (Image) componentContainer.findComponentById(ResourceTable.Id_iv_image);
        }
    }
}
